// 当文档加载完成后执行
document.addEventListener("DOMContentLoaded", async () => {
  // 获取DOM元素
  const customSpeedInput = document.getElementById("customSpeedInput");
  const addCustomSpeedBtn = document.getElementById("addCustomSpeedBtn");
  const customSpeedsList = document.getElementById("customSpeedsList");
  const enableShortcutsToggle = document.getElementById(
    "enableShortcutsToggle"
  );

  // 从存储中加载设置
  const settings = await loadSettings();

  // 初始化界面
  initializeUI(settings);

  // 添加自定义倍速按钮点击事件
  addCustomSpeedBtn.addEventListener("click", () => {
    addCustomSpeed();
  });

  // 自定义倍速输入框回车事件
  customSpeedInput.addEventListener("keydown", (event) => {
    if (event.key === "Enter") {
      addCustomSpeed();
    }
  });

  // 快捷键开关事件
  enableShortcutsToggle.addEventListener("change", () => {
    saveSettings({
      enableKeyboardShortcuts: enableShortcutsToggle.checked,
    });

    // 通知内容脚本更新设置
    notifyContentScript({
      type: "settingsChanged",
      settings: { enableKeyboardShortcuts: enableShortcutsToggle.checked },
    });
  });

  // 添加自定义倍速
  function addCustomSpeed() {
    const speedValue = parseFloat(customSpeedInput.value);

    // 验证输入
    if (!speedValue || speedValue < 0.1 || speedValue > 5) {
      alert("请输入有效的倍速值（0.1 到 5 之间）");
      return;
    }

    // 检查是否已存在该倍速
    if (settings.customSpeeds.includes(speedValue)) {
      alert("该倍速值已存在");
      return;
    }

    // 添加到设置
    settings.customSpeeds.push(speedValue);
    settings.customSpeeds.sort((a, b) => b - a); // 从大到小排序

    // 保存设置
    saveSettings({ customSpeeds: settings.customSpeeds });

    // 通知内容脚本更新设置
    notifyContentScript({
      type: "settingsChanged",
      settings: { customSpeeds: settings.customSpeeds },
    });

    // 更新界面
    updateCustomSpeedsList(settings.customSpeeds);

    // 清空输入框
    customSpeedInput.value = "";
  }

  // 删除自定义倍速
  function deleteCustomSpeed(speed) {
    // 从设置中移除
    settings.customSpeeds = settings.customSpeeds.filter((s) => s !== speed);

    // 保存设置
    saveSettings({ customSpeeds: settings.customSpeeds });

    // 通知内容脚本更新设置
    notifyContentScript({
      type: "settingsChanged",
      settings: { customSpeeds: settings.customSpeeds },
    });

    // 更新界面
    updateCustomSpeedsList(settings.customSpeeds);
  }

  // 更新自定义倍速列表
  function updateCustomSpeedsList(speeds) {
    // 清空列表
    customSpeedsList.innerHTML = "";

    // 添加每个倍速标签
    speeds.forEach((speed) => {
      const speedTag = document.createElement("div");
      speedTag.className = "custom-speed-tag";

      const speedText = document.createElement("span");
      speedText.textContent = `${speed}x`;

      const deleteBtn = document.createElement("span");
      deleteBtn.className = "delete-btn";
      deleteBtn.textContent = "×";
      deleteBtn.title = "删除";
      deleteBtn.addEventListener("click", () => {
        deleteCustomSpeed(speed);
      });

      speedTag.appendChild(speedText);
      speedTag.appendChild(deleteBtn);
      customSpeedsList.appendChild(speedTag);
    });
  }

  // 初始化界面
  function initializeUI(settings) {
    // 设置快捷键开关状态
    enableShortcutsToggle.checked = settings.enableKeyboardShortcuts;

    // 更新自定义倍速列表
    updateCustomSpeedsList(settings.customSpeeds);
  }

  // 从存储中加载设置
  async function loadSettings() {
    return new Promise((resolve) => {
      chrome.runtime.sendMessage({ action: "getSettings" }, (response) => {
        if (response) {
          resolve(response);
        } else {
          // 如果无法从后台获取，则直接从存储中获取
          chrome.storage.sync.get(
            {
              customSpeeds: [1.35, 1.45, 1.75],
              lastUsedSpeed: null,
              enableKeyboardShortcuts: true,
            },
            (items) => {
              resolve(items);
            }
          );
        }
      });
    });
  }

  // 保存设置到存储
  function saveSettings(settings) {
    chrome.runtime.sendMessage({
      action: "saveSettings",
      settings: settings,
    });
  }

  // 通知内容脚本
  function notifyContentScript(message) {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, message).catch(() => {
          // 忽略错误，内容脚本可能尚未加载
        });
      }
    });
  }
});
